package com.yjt.fresh.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.api.ApiApplyOrderBack;
import com.yjt.fresh.api.ApiImageUpload;
import com.yjt.fresh.base.BaseSimpleActivity;
import com.yjt.fresh.bean.BeanOrder;
import com.yjt.fresh.bean.BeanUploadIMG;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.dialog.CustomViewBottomDialog;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.widget.CustomToastResult;
import com.yjt.fresh.widget.RoundImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.zhouzhuo.zzimagebox.ZzImageBox;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by mcc on 2018/8/20.
 */

public class AtyApplyBack extends BaseSimpleActivity {
    @BindView(R.id.rlBack)
    RelativeLayout mRlBack;
    @BindView(R.id.ivAppAtyApplyBackContent)
    RoundImageView mIvContent;
    @BindView(R.id.tvAppAtyApplyBackContentTitle)
    TextView mTvContentTitle;
    @BindView(R.id.tvAppAtyApplyBackContentType)
    TextView mTvContentType;
    @BindView(R.id.tvAppAtyApplyBackContentNewPrice)
    TextView mTvNewPrice;
    @BindView(R.id.tvAppAtyApplyBackCount)
    TextView mTvCount;
    @BindView(R.id.tvAppAtyApplyBackBackGoods)
    TextView mTvBackGoods;
    @BindView(R.id.tvAppAtyApplyBackBackOnlyMoney)
    TextView mTvBackOnlyMoney;
    @BindView(R.id.ivAppAtyApplyBackSub)
    ImageView mIvSub;
    @BindView(R.id.tvAppAtyApplyBackBackCount)
    TextView mTvBackCount;
    @BindView(R.id.ivAppAtyApplyBackAdd)
    ImageView mIvAdd;
    @BindView(R.id.edtAppAtyApplyBackBackMoney)
    EditText mEdtBackMoney;
    @BindView(R.id.etAppAtyApplyBackReason)
    EditText mEtReason;
    @BindView(R.id.zzImageBoxAppAtyApplyBack)
    ZzImageBox mZzImageBox;
    @BindView(R.id.btnAppAtyApplyBackSubmit)
    Button mBtnSubmit;
    @BindView(R.id.tvAppAtyApplyBackReason)
    TextView mTvBackReason;
    @BindView(R.id.vAppAtyApplyBackCount)
    View mVCount;
    @BindView(R.id.llAppAtyApplyBackCount)
    LinearLayout mLlCount;
    private int mBackCount = 1;
    private BeanOrder.GOODSBean mGoodsBean;
    private double mSingleMoney;
    private double mTotalMoney;
    private String mBackType = "2";

    private String mImage1;
    private String mImage2;
    private String mImage3;
    private CustomViewBottomDialog mBottomDialog;

    @Override
    protected int getContentView() {
        return R.layout.app_aty_apply_back;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        mGoodsBean = (BeanOrder.GOODSBean) getIntent().getSerializableExtra(MyConstants.GOODS_OBJ);
        mTotalMoney = getIntent().getDoubleExtra(MyConstants.TOTAL_MONEY, 0);
        Glide.with(mContext).load(mGoodsBean.getSKU_IMG()).into(mIvContent);
        mTvContentTitle.setText(mGoodsBean.getTITLE());
        mTvContentType.setText(mGoodsBean.getSIZE());
        mSingleMoney = (mTotalMoney / mGoodsBean.getBUYCOUNT());
        mTvNewPrice.setText(mSingleMoney + "");
        mTvCount.setText("x" + mGoodsBean.getBUYCOUNT());
        mEdtBackMoney.setText(mSingleMoney + "");
    }

    @Override
    protected void initEvent() {
        initClick();
    }

    private void initClick() {
        mTvBackOnlyMoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvBackOnlyMoney.setTextColor(getResources().getColor(R.color.color_white));
                mTvBackGoods.setTextColor(getResources().getColor(R.color.color_43b624));
                mTvBackReason.setText("申请退款原因");
                mBackType = "1";
                mTvBackOnlyMoney.setBackgroundResource(R.drawable.zz_shape_43b624_5);
                mTvBackGoods.setBackgroundResource(R.drawable.zz_shape_43b624_border_5);
                mLlCount.setVisibility(View.GONE);
                mVCount.setVisibility(View.GONE);
                mEdtBackMoney.setText(mTotalMoney + "");
            }
        });

        mTvBackGoods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvBackGoods.setTextColor(getResources().getColor(R.color.white));
                mTvBackOnlyMoney.setTextColor(getResources().getColor(R.color.color_43b624));
                mTvBackReason.setText("申请退货原因");
                mBackType = "2";
                mTvBackGoods.setBackgroundResource(R.drawable.zz_shape_43b624_5);
                mTvBackOnlyMoney.setBackgroundResource(R.drawable.zz_shape_43b624_border_5);
                mLlCount.setVisibility(View.VISIBLE);
                mVCount.setVisibility(View.VISIBLE);
                mEdtBackMoney.setText((mSingleMoney * mBackCount) + "");
            }
        });
        mIvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBackCount < mGoodsBean.getBUYCOUNT()) {
                    mBackCount++;
                    mTvBackCount.setText(mBackCount + "");
                } else {
                    Toast.makeText(mContext, "最多为购买数量", Toast.LENGTH_SHORT).show();
                }

                mEdtBackMoney.setText((mBackCount * mSingleMoney) + "");
            }
        });

        mIvSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBackCount > 1) {
                    mBackCount--;
                    mTvBackCount.setText(mBackCount + "");
                } else {
                    Toast.makeText(mContext, "最少数量为1", Toast.LENGTH_SHORT).show();
                }
                mEdtBackMoney.setText((mBackCount * mSingleMoney) + "");
            }
        });
        mBtnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mEdtBackMoney.getText().toString())){
                    Toast.makeText(mContext, "退款金额不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(mEtReason.getText().toString())) {
                    Toast.makeText(mContext, "请填写原因", Toast.LENGTH_SHORT).show();
                    return;
                }
                

                submit();
            }
        });

        mZzImageBox.setOnImageClickListener(new ZzImageBox.OnImageClickListener() {

            @Override
            public void onImageClick(int position, String url, String realPath, int realType, ImageView iv) {

            }

            @Override
            public void onDeleteClick(int position, String url, String realPath, int realType) {
                mZzImageBox.removeImage(position);
            }

            @Override
            public void onAddClick() {
                if (mBottomDialog == null) {
                    mBottomDialog = new CustomViewBottomDialog(mContext);
                    initAlterPhotoDialogView();
                    mBottomDialog.builder();
                }
                mBottomDialog.show();
            }
        });

        mEdtBackMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString())) {
                    if (Double.valueOf(s.toString()) > mTotalMoney){
                        mEdtBackMoney.setText(mTotalMoney+"");
                    }
                }else {
                    mEdtBackMoney.setText("0");
                }
            }
        });
        mRlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void submit() {
        ApiApplyOrderBack apiApplyOrderBack = new ApiApplyOrderBack(new HttpOnNextListener<BaseResultEntity>() {

            @Override
            public void onNext(BaseResultEntity baseResultEntity) {
                CustomToastResult.show("提交成功");
                finish();
            }

            @Override
            public void onReLogin() {

            }
        },mContext,true,false,false);
        Map<String,Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        map.put("ORDERSITEM_ID",mGoodsBean.getORDERSITEM_ID());
        map.put("COUNT",mBackCount+"");
        map.put("BACK_MONEY", mEdtBackMoney.getText().toString());
        map.put("BACK_TYPE",mBackType);
        map.put("PROBLEM_DESCRIBE",mEtReason.getText().toString());
        if (mImage1 != null) {
            map.put("DESCRIBE1_IMG",mImage1);
        }
        if (mImage2 != null){
            map.put("DESCRIBE2_IMG",mImage2);
        }
        if (mImage3 != null){
            map.put("DESCRIBE3_IMG",mImage3);
        }

        apiApplyOrderBack.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiApplyOrderBack);
    }

    private void initAlterPhotoDialogView() {
        View view = View.inflate(mContext, R.layout.app_dialog_alter_photo, null);
        TextView tvCamera = view.findViewById(R.id.tvAppDialogAlterPhotoCamera);
        TextView tvAlbum = view.findViewById(R.id.tvAppDialogAlterPhotoAlbum);
        TextView tvCancel = view.findViewById(R.id.tvAppDialogAlterPhotoCancel);
        mBottomDialog.setView(view);

        tvCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                startActivityForResult(intent, MyConstants.PICK_IMG);
                mBottomDialog.dismiss();
            }
        });

        tvAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ImageGridActivity.class);
                startActivityForResult(intent, MyConstants.PICK_IMG);
                mBottomDialog.dismiss();
            }
        });

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialog != null) {
                    mBottomDialog.dismiss();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MyConstants.PICK_IMG && resultCode == ImagePicker.RESULT_CODE_ITEMS && data != null) {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            mZzImageBox.addImage(images.get(0).path);
            uploadImage(images.get(0).path);
        }

    }

    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BeanUploadIMG>() {
        @Override
        public void onNext(BeanUploadIMG data) {
            if (mImage1 == null){
                mImage1 = data.getIMG_URL();
            }else if (mImage2 == null){
                mImage2 = data.getIMG_URL();
            }else {
                mImage3 = data.getIMG_URL();
            }
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void uploadImage(String path) {
        File file = new File(path);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
        MultipartBody.Part part1 = MultipartBody.Part.createFormData("IMG", file.getName(), requestBody);
        ApiImageUpload postEntity = new ApiImageUpload(simpleOnNextListener, mContext, true, false, true);
        postEntity.setPart(part1);
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(postEntity);
    }

}
